import cv2
import numpy as np

# 打开摄像头
cap = cv2.VideoCapture(1)

# 设置摄像头参数
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
cap.set(cv2.CAP_PROP_EXPOSURE, -5)

while True:
    # 读取一帧
    ret, frame = cap.read()
    if not ret:
        break
    
    cv2.imshow('before', frame)

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_red = np.array([0, 127, 70])
    upper_red = np.array([12, 255, 255])
    mask1 = cv2.inRange(hsv, lower_red, upper_red)
    lower_red = np.array([180, 120, 70])
    upper_red = np.array([180, 255, 255])
    mask2 = cv2.inRange(hsv, lower_red, upper_red)
    mask = mask1 | mask2
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for contour in contours:
        area = cv2.contourArea(contour)
        if area < 1000:
            # print(1)
            continue
        else:
            x, y, w, h = cv2.boundingRect(contour)
            print (x, y, w, h, 0)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 3)
            
            
    # 显示原始帧和边缘检测后的帧
    cv2.imshow('after', frame)

    # 按下 'q' 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头并关闭所有窗口
cap.release()
cv2.destroyAllWindows()

